package lyttest.config;

import lyttest.schedule.RedisKeyQuartzJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    @Value("${spring.quartz.cron}")
    private String redisCron;

    /**
     * 创建定时任务
     */
    @Bean
    public JobDetail quartzTestDetail() {
        JobDetail jobDetail = JobBuilder.newJob(RedisKeyQuartzJob.class)
                .withIdentity("quartz_redisKey")
                .usingJobData("userName", "key")
                .storeDurably()
                .build();
        return jobDetail;
    }

    /**
     * 创建触发器
     */
    @Bean
    public Trigger quartzTestJobTrigger() {
        //每隔30秒执行一次，但是cron表达式机制不会在应用启动后立即执行
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(redisCron);

        //创建触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(quartzTestDetail())
                .withIdentity("quartzJobTrigger", "quartz_redisKey_job_trigger")
                .withSchedule(cronScheduleBuilder)
                .build();
        return trigger;
    }

    // 定义触发器，确保任务在应用启动后立即执行一次
    @Bean
    public Trigger myTrigger(JobDetail myJobDetail) {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(0)  // 立即执行
                .withRepeatCount(0);       // 不重复执行

        return TriggerBuilder.newTrigger()
                .forJob(myJobDetail)
                .withIdentity("myTrigger")
                .withSchedule(scheduleBuilder)
                .startNow()  // 立即启动
                .build();
    }
}